package com.ericsson.enap.modules.backup.task;

import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.*;
import com.ericsson.enap.modules.backup.constant.BackupConstant;
import com.ericsson.enap.modules.backup.service.ImsDataBackupService;
import com.ericsson.enap.modules.backup.utils.ExecCmd;
import com.ericsson.enap.modules.sys.entity.EnipNetelement;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: ImsDataBackup 主任务
 * @author: wangjingshi
 * @create: 2021-05-31 16:00
 */
@Component
public class ImsDataBackupTask implements ManualTask {

    private Logger log = LoggerUtils.Logger(LogFileName.ImsDataBackupJob);

    @Autowired
    private ImsDataBackupService imsDataBackupService;
    @Autowired
    private EpcDictService epcDictService;
    @Value("${collectorIp}")
    private String collectorIp;

    private int JobNo;

    @Override
    public void execute() {
        long startTime = new Date().getTime();
        log.info(JobNo+" ==== startTime :"+startTime);
        cleanOldFile();
        ExecCmd.executeKillCmd("ps -ef |grep node_cmd_run"+JobNo+".pl |grep -v grep|awk '{print $2}'|xargs kill -9",JobNo);
        //1.查询当前采集器配置了哪些网元需要进行下载
        log.info(JobNo+" ======= bizType:"+10+" ======= collectorIp:"+collectorIp);
        List<EnipNetelement> list = imsDataBackupService.queryNetelementList(10,collectorIp);
        List<EnipNetelement> netList = list.stream().filter(x->x.getType()!=104).collect(Collectors.toList());
        List<EnipNetelement> cgList = list.stream().filter(x->x.getType()==104).collect(Collectors.toList());
        String date = DateUtils.formatDate(new Date());//yyyy-MM-dd
        String dateTime = DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
        for (EnipNetelement enipNetelement:netList){
            log.info(JobNo+" ======="+enipNetelement.getName()+"======= start =======");
            switch(JobNo){
                case 1:
                    imsDataBackupService.execBackupFile(enipNetelement,date,JobNo);
                    imsDataBackupService.execSysLog(enipNetelement,date,JobNo);
                    imsDataBackupService.execSafLog(enipNetelement,date,JobNo);
                    imsDataBackupService.execCommonLog(enipNetelement,date,"/cluster/storage/no-backup/cdclsv/log/lpmsv/","consoleLog",JobNo);
                    break;
                case 2:
                    imsDataBackupService.execCommonLog(enipNetelement,date,"/cluster/storage/no-backup/diacc/log/","c-diameterLog",JobNo);
                    imsDataBackupService.execCommonLog(enipNetelement,date,"/cluster/storage/no-backup/cdclsv/log/","additionalvDicosLogs",JobNo);
                    break;
                case 3:
                    imsDataBackupService.execLogDump(enipNetelement,date,"logdump",JobNo,dateTime);
                    cleanOldData3(date, enipNetelement);
                    break;
            }
            log.info(JobNo+" ======="+enipNetelement.getName()+"======= end =======");
        }
        //处理新需求，每天的凌晨3点执行收集指令
        if(JobNo==4){
            imsDataBackupService.execSshCollectFile(cgList,date,JobNo);
        }
        long endTime = new Date().getTime();
        log.info(JobNo+" ==== total time :"+(endTime-startTime)/1000/(double)60.00);
    }

    private void cleanOldData3(String date, EnipNetelement enipNetelement) {
        String cleanDays = epcDictService.selectEpcDict(new EpcDict(BackupConstant.cleanLogdump)).getKeyValue();
        String cleanDate = DateUtils.beforNumDay(new Date(),-Integer.parseInt(cleanDays));
        String cleanDir = BackupConstant.localPath + cleanDate + "/" +
                enipNetelement.getType() + "/" + enipNetelement.getName() + "/logdump";
        File cleanFile = new File(cleanDir);
        FileUtil.deleteDir(cleanFile);
        imsDataBackupService.deleteOldDumpsData(cleanDate);

    }

    //清除过期数据
    private void cleanOldFile() {
        //默认清理91天的文件夹
        String cleanDays = epcDictService.selectEpcDict(new EpcDict("sysLog")).getKeyValue();
        String cleanDate = DateUtils.beforNumDay(new Date(),-Integer.parseInt(cleanDays)-1);
        String dir = BackupConstant.localPath;
        File file = new File(dir);
        File[] files = file.listFiles();
        if(files!=null){
            for (File f:files){
                if(f.getName().compareTo(cleanDate)<=0){
                    try {
                        log.info(JobNo+" ======= delete file ======="+f.getAbsolutePath());
                        FileUtils.deleteDirectory(f);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public int getJobNo() {
        return JobNo;
    }

    public void setJobNo(int jobNo) {
        JobNo = jobNo;
    }

}
